package com.example.weixinsystem.security.handler;

import com.alibaba.fastjson2.JSON;
import com.weixin.common.core.constant.HttpStatus;
import com.weixin.common.core.domain.Result;
import com.weixin.common.core.form.LoginUserDetails;
import com.weixin.common.core.utils.JwtUtils;
import com.weixin.common.core.utils.SecurityUtil;
import com.weixin.common.core.utils.TokenUtil;
import com.weixin.common.core.utils.WebUtil;
import com.weixin.common.redis.service.RedisService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 1.0.0
 * @className: LogoutSuccessHandlerImpl
 * @description: 自定义退出处理类 返回成功
 * @author: zhangjunfa
 * @date: 2023/5/29 16:10
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    private final RedisService redisService;

    public LogoutSuccessHandlerImpl(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = SecurityUtil.getToken(request);
        String cacheKey = TokenUtil.getRedisCacheKey(token);
        LoginUserDetails loginUser = redisService.getCacheObject(cacheKey);
        if (!ObjectUtils.isEmpty(loginUser)) {
            // 删除用户缓存记录
            redisService.deleteObject(cacheKey);
        }
        WebUtil.renderString(response, JSON.toJSONString(Result.fail(HttpStatus.SUCCESS, "退出成功")));
    }
}
